package xj.graph2d.command;

import java.awt.geom.Rectangle2D;

import xj.graph2d.DrawShape;
import xj.graph2d.Group;
import xj.graph2d.SimpleDrawDocument;
import xj.graph2d.SimpleDrawView;
import xj.graph2d.TextShape;

public class AddShapeCommand 
  extends AbstractCommand {

  public AddShapeCommand(SimpleDrawView view, SimpleDrawDocument doc,
			 DrawShape shape) {
    this(view, doc, null, shape, -1);
  }

  public AddShapeCommand(SimpleDrawView view, SimpleDrawDocument doc,
			 DrawShape parent, DrawShape shape) {
    this(view, doc, parent, shape, -1);
  }

  public AddShapeCommand(SimpleDrawView view, SimpleDrawDocument doc,
			 DrawShape parent, DrawShape shape, int pos) {
    super(view, doc);
    this.shape = shape;
    this.parent = parent;
    this.pos = pos;
  }

  public void execute() {
    if (shape != null) {
      DrawShape selected = doc.getSelectedShape();
      doc.setSelectedShape(null);
      canvas.repaintShape(selected);
      if (parent == null) {
	doc.add(shape, true);
	canvas.repaintShape(shape);
      } else {
	if (pos == -1) {
	  pos = parent.addShape(shape);
	} else {
	  parent.insertShapeAt(shape, pos);
	}
	if (shape instanceof TextShape) {
	  TextShape text = (TextShape) shape;
	  // text.setPosition(text.getEnd1(), true);
	  text.setPosition(text.getPosition(), true);
	}
	doc.shapeAdded(shape);
	parent.componentDimensionChanged(shape);
	canvas.repaintShape(parent);
      }
    }
  }

  public void undo() {
    if (shape != null) {
      Rectangle2D r2;
      if (parent == null) {
	doc.remove(shape);
	r2 = shape.getRepaintRect();
      } else {
	r2 = parent.getRepaintRect();
	pos = parent.indexOfShape(shape);
	if (pos >= 0) {
	  r2 = (Rectangle2D) r2.clone();
	  parent.removeShape(pos);
	  doc.shapeRemoved(shape);
	  if (shape instanceof TextShape) {
	    TextShape text = (TextShape) shape;
	    TextShape nextline = text.getNextLine();
	    if (nextline != null) {
	      nextline.setPosition(text.getEnd1(), true);
	    }
	  }
	  // parent.fitComponents();
	  parent.doLayout();
	}
      }
      canvas.repaintRect(r2, true, true);
    }
  }

  @Override
  public String toString() {
    String s = "";
    if (shape != null) {
      if (shape instanceof TextShape) {
	TextShape text = (TextShape) shape;
	s = (text.getName() + " \"" + text.getString() + "\"");
      } else if (shape instanceof Group) {
	s = shape.toString();
      } else {
	s = (shape.getName() + " " + shape.getBoundsString());
      }
    }
    return (getClass().getName() + ": " + s);
  }

  protected DrawShape shape;

  protected DrawShape parent = null;

  protected int pos = -1;

}
